from flask import Flask, request, jsonify, send_from_directory
import os
import sys

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from models import MessageTask
from storage import TaskStorage
from message_sender import send_message

app = Flask(__name__)

# 配置前端静态文件访问
@app.route('/frontend/<path:filename>')
def serve_frontend(filename):
    frontend_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'frontend')
    return send_from_directory(frontend_dir, filename)

# 首页路由
@app.route('/')
def index():
    return serve_frontend('index.html')

@app.route('/tasks', methods=['GET'])
def get_all_tasks():
    """获取所有任务"""
    tasks = TaskStorage.load_all_tasks()
    return jsonify([task.to_dict() for task in tasks])

@app.route('/tasks/<task_id>', methods=['GET'])
def get_task(task_id):
    """获取单个任务"""
    task = TaskStorage.get_task_by_id(task_id)
    if task:
        return jsonify(task.to_dict())
    return jsonify({'error': 'Task not found'}), 404

@app.route('/tasks', methods=['POST'])
def create_task():
    """创建新任务"""
    data = request.json
    required_fields = ['title', 'message_type', 'content', 'webhook_url']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'Missing required field: {field}'}), 400

    if data['message_type'] not in ['text', 'news']:
        return jsonify({'error': 'Invalid message type, must be "text" or "news"'}), 400

    # 对于news类型，确保content是有效的JSON
    if data['message_type'] == 'news':
        try:
            # 尝试解析content为JSON
            if isinstance(data['content'], str):
                news_items = json.loads(data['content'])
            else:
                news_items = data['content']
            # 验证news_items的结构
            if not isinstance(news_items, list):
                raise ValueError('News content must be a list')
            for item in news_items:
                if not isinstance(item, dict) or 'title' not in item or 'description' not in item or 'url' not in item or 'picurl' not in item:
                    raise ValueError('Each news item must contain title, description, url and picurl')
            # 转换为JSON字符串存储
            data['content'] = json.dumps(news_items)
        except Exception as e:
            return jsonify({'error': f'Invalid news content: {str(e)}'}), 400

    task = MessageTask(
        title=data['title'],
        message_type=data['message_type'],
        content=data['content'],
        webhook_url=data['webhook_url']
    )
    TaskStorage.save_task(task)
    return jsonify(task.to_dict()), 201

@app.route('/tasks/<task_id>', methods=['PUT'])
def update_task(task_id):
    """更新任务"""
    task = TaskStorage.get_task_by_id(task_id)
    if not task:
        return jsonify({'error': 'Task not found'}), 404

    data = request.json
    if 'message_type' in data and data['message_type'] not in ['text', 'news']:
        return jsonify({'error': 'Invalid message type, must be "text" or "news"'}), 400

    # 对于news类型，确保content是有效的JSON
    if 'message_type' in data and data['message_type'] == 'news' and 'content' in data:
        try:
            # 尝试解析content为JSON
            if isinstance(data['content'], str):
                news_items = json.loads(data['content'])
            else:
                news_items = data['content']
            # 验证news_items的结构
            if not isinstance(news_items, list):
                raise ValueError('News content must be a list')
            for item in news_items:
                if not isinstance(item, dict) or 'title' not in item or 'description' not in item or 'url' not in item or 'picurl' not in item:
                    raise ValueError('Each news item must contain title, description, url and picurl')
            # 转换为JSON字符串存储
            data['content'] = json.dumps(news_items)
        except Exception as e:
            return jsonify({'error': f'Invalid news content: {str(e)}'}), 400

    task.update(
        title=data.get('title'),
        message_type=data.get('message_type'),
        content=data.get('content'),
        webhook_url=data.get('webhook_url')
    )
    TaskStorage.save_task(task)
    return jsonify(task.to_dict())

@app.route('/tasks/<task_id>', methods=['DELETE'])
def delete_task(task_id):
    """删除任务"""
    success = TaskStorage.delete_task(task_id)
    if success:
        return jsonify({'message': 'Task deleted successfully'})
    return jsonify({'error': 'Task not found'}), 404

@app.route('/tasks/<task_id>/send', methods=['POST', 'GET'])
def send_task_message(task_id):
    """执行任务，发送消息"""
    task = TaskStorage.get_task_by_id(task_id)
    if not task:
        return jsonify({'error': 'Task not found'}), 404

    try:
        result = send_message(task)
        return jsonify({
            'message': 'Message sent successfully',
            'result': result
        })
    except Exception as e:
        return jsonify({'error': f'Failed to send message: {str(e)}'}), 500

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)